package net.yegong.gdal;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import net.yegong.gdal.Gdal.Utility;

public class GdalTranslate {

	public GdalTranslate(File file) throws Exception {
		GdalInfo info = new GdalInfo(file);
		band = info.getBands();
		source = String.format("\"%s\"", file.getAbsoluteFile());
	}

	public List<File> convertToBitmapFiles() throws Exception {
		List<File> bitmapFiles = new ArrayList<File>();
		for (int i = 1; i <= band; ++i) {
			File file = new File(String.format("tmp\\tmp-%d.bmp", i));
			bitmapFiles.add(file);
			String path = String.format("\"%s\"", file.getAbsoluteFile());
			String stdout = Gdal.run(Utility.GDAL_TRANSLATE, "-ot Byte", "-of BMP", "-b", String.valueOf(i), source, path);
			System.out.println(stdout);
		}
		return bitmapFiles;
	}

	public List<BufferedImage> convertToBitmap() throws Exception {
		List<File> bitmapFiles = convertToBitmapFiles();
		List<BufferedImage> images = new ArrayList<BufferedImage>();
		for (File f : bitmapFiles) {
			BufferedImage image = ImageIO.read(f);
			images.add(image);
		}
		return images;
	}

	private final int band;
	private final String source;
}
